package com.exam.sms.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.utils.StringUtils;
import com.exam.sms.config.SmsProperties;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName : SmsUtils
 * @Description : 发送信息
 * @Author : WHB
 */

@Component
@EnableConfigurationProperties(SmsProperties.class)
public class SmsUtils {

    @Autowired
    private SmsProperties prop;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "sms:phone:";
    private static final long SMS_MIN =  600000;

    public CommonResponse SendSms(String phoneNumber,String signName,String templateCode,String templateParam) {
        //判断读取时间
        String key = KEY_PREFIX +phoneNumber;
        String lastTime = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotEmpty(lastTime)){
            Long last = Long.valueOf(lastTime);
            if (System.currentTimeMillis() - last <SMS_MIN){
                return null;
            }
        }

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou","LTAI4FwGfyR4i6b2z9Y3fyMy", "u25oY9DdkoQlIXUGJIqJkfqlFDe5g4");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", templateParam);

        CommonResponse response = new CommonResponse();
        try {
            response = client.getCommonResponse(request);
            System.out.println(response.getData());
            //发送短信成功之后，写入redis,指定生存时间为1分钟
            redisTemplate.opsForValue().set(key,String.valueOf(System.currentTimeMillis()),5, TimeUnit.MINUTES);

        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return response;
    }

}
